package com.haixee.parkdemo.auth.service.impl;

import com.haixee.parkdemo.auth.dao.*;
import com.haixee.parkdemo.auth.enums.RoleScope;
import com.haixee.parkdemo.auth.model.Role;
import com.haixee.parkdemo.auth.model.Tenant;
import com.haixee.parkdemo.auth.service.TenantService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


@Service
public class TenantServiceImpl implements TenantService {

    @Autowired
    private TenantCustomMapper tenantCustomMapper;

    @Autowired
    private TenantMapper tenantMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private RoleScopeMapper roleScopeMapper;

    @Override
    public List<Tenant> selectAll() {
        return tenantCustomMapper.selectAll();
    }

    @Override
    @Transactional
    public void addTenant(String name) {
        Tenant tenant = new Tenant();
        tenant.setName(name);
        tenantMapper.insertSelective(tenant);

        // 自动添加园区管理员角色
        Role role = new Role();
        role.setTenantId(tenant.getId());
        role.setName(tenant.getName() + "管理员");
        roleMapper.insertSelective(role);

        com.haixee.parkdemo.auth.model.RoleScope roleScope = new com.haixee.parkdemo.auth.model.RoleScope();
        roleScope.setDataScope(RoleScope.ALL.getScope());
        roleScope.setRoleId(role.getId());
        roleScopeMapper.insertSelective(roleScope);
    }

    @Override
    public void updateTenant(Integer id, String name) {
        Tenant tenant = new Tenant();
        tenant.setId(id);
        tenant.setName(name);
        tenantMapper.updateByPrimaryKeySelective(tenant);
    }
}
